<template>
  <el-card shadow="hover">

    <template #header>

      <el-button type="primary" :icon="Plus" @click="addcommodity">

        添加</el-button>
    </template>


    <!-- 表格 -->
    <el-table :data="tbleData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="date" label="序号" type="index" width="80" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="address" label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width:100px; height:100px ;">
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column prop="address" label="操作">
        <template #default="scope">
          <el-button size="small" :icon="Pointer" type="warning" @click="handleEdit(scope.$index, scope.row)">
          </el-button>
          <el-button :icon="DeleteFilled" size="small" type="danger" @click="handleDelete(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->

    <el-pagination style="margin-top: 20px; text-align: center;" v-model:currentPage="currentPage"
      v-model:page-size="pageSize" :page-sizes="[3, 6, 9,]" :small="small" :disabled="disabled"
      :background="background" layout=" prev, pager, next, jumper,-> ,sizes,total, " :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

  </el-card>



      <!-- 添加品牌对话框 -->

  <el-dialog v-model="dialogTableVisible" >
<span role="heading" class="eldialogtitle" >{{twoAspects}}品牌</span>

  <el-form
    ref="ruleFormRef"
    status-icon
    label-width="120px"
    class="demo-ruleForm"
    :rules="rules"  
  >
    <el-form-item label="品牌名称" prop="tmName">
      <el-input v-model="form.tmName"   autocomplete="off"  style="width: 78%; "/>
    </el-form-item>
    <el-form-item label="品牌LOGO" prop="checkPass">
       <el-upload
    class="avatar-uploader"
    :action="`${BASE_URL}/admin/product/upload`"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
  
    </el-form-item>

    <el-form-item style="margin-left: 700px; margin-bottom: 0px;">
      <el-button @click="resetForm()">取消</el-button>
      <el-button type="primary" @click="submitForm()"
        >确定</el-button
      >
      </el-form-item>

  </el-form>

  </el-dialog>

</template>

<script lang="ts">
export default {
  name: 'tradeemark'
}


</script>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus' // 接口
import type { UploadProps } from 'element-plus'
import type {tableData, sztableData} from '@/api/model/trademark'
import { reqbaseTrademark, reqbaseTrademarkAmend, reqbaseTrademarkData, reqbaseTrademarkdl } from '@/api/product/tradeemark'
import { ref, onMounted,reactive, } from 'vue'

import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
  DeleteFilled,
  Pointer
} from '@element-plus/icons-vue'

//添加品牌
const dialogTableVisible = ref<boolean>(false)
const dialogFormVisible = ref<boolean>(false)
const formLabelWidth = '140px'

// 定义个值和el-for绑定
const ruleFormRef=ref<FormInstance>()

//编辑添加数据
const twoAspects=ref<string>('添加')


//表格数据
const tbleData = ref<sztableData>([])

//进度条加载中效果
const loading = ref<boolean>(false)
//分页器

//总页数
const total = ref()
//当前页
const currentPage = ref(1)
//每页几条
const pageSize = ref(3)
const small = ref<boolean>(false)
const background = ref<boolean>(false)
const disabled = ref<boolean>(false)


//上传框
const imageUrl = ref<string>('')

//添加图片容器
const form = reactive<tableData>({
     tmName: '',
    logoUrl:''
})


// 输入框校验规则
const rules = reactive<FormRules>({
  tmName: [
   { required: true, message: '请添加品牌名称', trigger: 'blur' },
    { min: 1, max: 6, message: '长度在1到6之间', trigger: 'blur' }
  ],
  logoUrl: [{
    required: true, message: '请选择要上传的图片', trigger: 'change' 
  }]
})


//弹出对话框
const addcommodity = () => {
   imageUrl.value=''
  form.tmName=''
  dialogTableVisible.value=true
}

 // 上传图片地址，会从.env.development中加载
const BASE_URL = import.meta.env.VITE_API_URL



// 收集的数据表单的品牌对象
const initTrademark = () => ({ id:'', tmName: '', logoUrl: '' })
let trademark = reactive(initTrademark());



//取消上传
const resetForm = () => {
  // if (!formEl) return
  // formEl.resetFields()
  dialogTableVisible.value = false
  twoAspects.value = '添加'
  form.tmName = ''
      
   imageUrl.value=''
}

//添加商品请求

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log('sdfsdf',response.data);
  
  form.logoUrl=response.data
}

//上传图片校验规则
// 限定图片上传的格式及大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  const imgTypes = ['image/jpeg','image/jpg','image/png','image/gif']
  // if (rawFile.type !== 'image/jpeg') {
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error('上传图片的格式只能是jpg/png/jepg,请重新选择')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M,请重新选择...!')
    return false
  }
  return true
}

//添加或修改上传

const submitForm = async () => {
 
  trademark.tmName=form.tmName
  trademark.logoUrl = imageUrl.value
//   if (!formEl) return
//     await formEl.validate((valid, fields) => {
//     if (valid) {
    
//     } else {
//       console.log('error submit!', fields)
//     }
//   })
// }
  if (!trademark.id) {

   await reqbaseTrademark(form.tmName,form.logoUrl)
  
  } else {
 await reqbaseTrademarkAmend(trademark)
  
 }

    
 

  dialogTableVisible.value = false
  // console.log('xxx',result);
  
  getreqbaseTrademarkDataMAX()
  twoAspects.value = '添加'
  form
}


// 编辑方法
const handleEdit = (index: number, row:number) => {
  console.log(row);
  trademark.id=row.id
  
   form.tmName=row.tmName
   imageUrl.value=row.logoUrl
  twoAspects.value='编辑'
  dialogTableVisible.value = true

 
}

// 删除方法
const handleDelete = (row: number) => {
  loading.value = true
  delreqbaseTrademarkdl(row)
  getreqbaseTrademarkDataMAX()
  console.log(row)
  loading.value = false
}

//每页几条数据
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getreqbaseTrademarkDataMAX()
  console.log('12123', `${val} items per page`)
}

//当前所在页
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  getreqbaseTrademarkDataMAX()

}

//定义发送获取列表数据请求
const getreqbaseTrademarkData = async (currentPage: number, pageSize: number) => {
  loading.value = true
  const result = await reqbaseTrademarkData(currentPage, pageSize)
  tbleData.value = result.records
  total.value = result.total
  console.log('',result)
  loading.value = false
}

//定义删除列表请求
const delreqbaseTrademarkdl = async (id: number) => {
  await reqbaseTrademarkdl(id)
}


//封装请求函数
const getreqbaseTrademarkDataMAX = () => {
   getreqbaseTrademarkData(currentPage.value, pageSize.value)
}
//在页面挂载完毕就发送请求
onMounted(() => {
  
  getreqbaseTrademarkDataMAX()
  loading.value = false

})

</script>


<!-- 添加品牌 -->
<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<!-- //上传品牌 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.eldialogtitle{
  display: block;
 color:#303133;
 font-size: 18px;
margin-top: -40px;
float: left;
 
}
</style>